include Gosu
include Globals

class BlackHole < GameObject
  ACCEL = -0.020  # acceleration of gravity. Modified according to player's distance from source.

  def initialize(screen, game)
    super(screen)
    @screen = screen
    @game = game
    @images = {}
    @soundfx = {}

    @sprite = game.load_tiles("black_hole.png", 80, 80)
    @sprite_f = 0.0

    appear_sound = game.sounds["black_hole_appear_remix.ogg"]
    implode_sound = game.sounds["black_hole_implode_remix.ogg"]
    @soundfx["appear"] = appear_sound
    @soundfx["explode"] = implode_sound

    @x, @y = rand(WIDTH - 200) + 100, rand(HEIGHT - 200) + 100
    # 100 px border around the game window
    @angle = 0
    Task.new(@screen, @game, :wait => 480) { implode }
    @factor_x = @factor_y = 1
    @destroyed = false
    if @screen.game_options["sound"]
      @soundfx["appear"].play.volume = @screen.game_options["sound_volume"]
    end
  end

  def update
    @sprite_f += 0.33
    # advance one sprite frame every three game loops
    @sprite_f %= @sprite.size
    # experimentation was used to determine proper value of "a"
    # once "s" is found, the players velocity is determined by:
    # v = u + at
    @screen.players.each do |player|
      # use the dist between player and hole to calculate grav magnitude
      dist = distance(player.x, player.y, @x, @y)
      magn_x = (HEIGHT - dist).to_f / 220.0 # yes, HEIGHT for both
      magn_y = (HEIGHT - dist).to_f / 220.0
      magn_x, magn_y = 0, 0 if magn_x <= 0 # allows an out of range
      vx, vy = player.vel_x, player.vel_y
      accel = ACCEL * (magn_x**2 + magn_y**2)**(0.5)
        # accel will change in accordance to player's distance from hole
      theta = angle(@x, @y, player.x, player.y)
        # theta is the angle from the hole to the player
      ax = offset_x(theta, accel) # x component of gravity
      ay = offset_y(theta, accel) # y component
      player.vel_x = vx + ax # v = u + at, t = 1 frame
      player.vel_y = vy + ay # v = u + at, t = 1 frame

      #player.x += offset_x(angle, magn_x) <--this was part of the old
      #player.y += offset_y(angle, magn_y) <--  crappy black hole physics
    end
    @angle += 0.5 # image spin effect
    if @destroyed
      @factor_x -= 0.02 # shrink to nothing
      @factor_y -= 0.02
    end
    return false if @factor_x <= 0
    true
  end

  def draw
    @sprite[@sprite_f.to_i].draw_rot(@x, @y, ASTEROID_Z, @angle, 0.5, 0.5, @factor_x, @factor_y)
  end

  def obj_id
    return :black_hole
  end

  def implode
    if @screen.game_options["sound"]
      @soundfx["explode"].play.volume = @screen.game_options["sound_volume"]
    end
    @destroyed = true
  end

end
